<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_Article extends Controller_Base {
 	
	const INDEX_PAGE='article';

  public function action_index() {
    $articles = ORM::factory('article')->find_all(); // loads all article object from table
    $this->template->content = View::factory('article/index')
      ->bind('articles', $articles);
  }

  //View single article
  public function action_view() {
      $article_id = $this->request->param('id');
      $article = ORM::factory('article', $article_id);

      $view = new View('article/single');
      $view->set("article", $article);
       
      $this->template->set('content', $view);
  }

  // loads the new article form
  public function action_new() {
      $article = new Model_Article();
      $errors = array(); //Validattion

      $view = new View('article/edit');
      $view->set("article", $article);
      $view->set('errors', $errors);
      $this->template->set('content',$view);
  }

  // save the article
  public function action_post() {
      $article_id = $this->request->param('id');
      $article = new Model_Article($article_id);
      $article->values($_POST); // populate $article object from $_POST array
      
      try {
          $article->save(); // saves article to database
          HTTP::redirect(self::INDEX_PAGE);
      } catch (ORM_Validation_Exception $ex) {
          $errors = $ex->errors('validation');
      }
       
      $view = new View('article/edit');
      $view->set("article", $article);
      $view->set('errors', $errors);
       
      $this->template->set('content', $view);
  }

   // edit the article
  public function action_edit() {
      $article_id = $this->request->param('id');
      $article = new Model_Article($article_id);

      $view = new View('article/edit');
      $view->set("article", $article);
       
      $this->template->set('content',$view);
  }

  // delete the article
  public function action_delete() {
      $article_id = $this->request->param('id');
      $article = new Model_Article($article_id);

      $article->delete();
      HTTP::redirect(self::INDEX_PAGE);
  }
 
}